package com.sdtv.mediunfusion.mvp.ui.punch;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.sdtv.basemodule.annotations.CreatePresenter;
import com.sdtv.basemodule.annotations.PresenterVariable;
import com.sdtv.basemodule.base.BaseActivity;
import com.sdtv.basemodule.bean.Results;
import com.sdtv.basemodule.router.ARouterUtils;
import com.sdtv.basemodule.utils.ClickProxy;
import com.sdtv.mediunfusion.R;
import com.sdtv.mediunfusion.base.config.MediumApplication;
import com.sdtv.mediunfusion.bean.PunchBean;
import com.sdtv.mediunfusion.bean.UserIdentify;
import com.sdtv.mediunfusion.mvp.contract.MainContract;
import com.sdtv.mediunfusion.mvp.presenter.PunchPresenter;
import com.sdtv.mediunfusion.utils.RouterPath;
import com.sdtv.mediunfusion.utils.ViewBgUtils;
import com.sdtv.mediunfusion.widget.MyMonthView;
import com.sdtv.mediunfusion.widget.MyWeekView;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 打卡记录页面
 * 用来展示用户的打卡记录
 */
@Route(path = RouterPath.TO_PUNCHLOGGING_ACTIVITY)
@CreatePresenter(presenter = PunchPresenter.class)
public class PunchLoggingActivity extends BaseActivity implements
        CalendarView.OnMonthChangeListener,
        CalendarView.OnCalendarSelectListener, MainContract.PunchView {


    @BindView(R.id.pl_backButton)
    ImageView backButton;
    @BindView(R.id.pl_calendarView)
    CalendarView calendarView;
    @BindView(R.id.title_month)
    TextView titleMonth;
    @BindView(R.id.pl_settingAmTime)
    TextView settingAmTime;
    @BindView(R.id.pl_amLogging)
    TextView amLogging;
    @BindView(R.id.pl_settingPmTime)
    TextView settingPmTime;
    @BindView(R.id.pl_pmLogging)
    TextView pmLogging;
    @BindView(R.id.pl_circleImg)
    View circleImgAm;
    @BindView(R.id.pl_amTextView)
    TextView amTextView;
    @BindView(R.id.pl_circleImgP)
    View circleImgPm;
    @BindView(R.id.pl_pmTextView)
    TextView pmTextView;
    @BindView(R.id.pl_amPart)
    LinearLayout plAmPart;
    @BindView(R.id.pl_pmPart)
    LinearLayout plPmPart;
    // 获取打卡记录
    @PresenterVariable
    PunchPresenter punchPresenter;
    // 这个用来设置日历UI
    private HashMap<String, Calendar> dataMap = new HashMap<>();
    // 这个用来设置当日的打卡对象
    private HashMap<String, PunchBean> listMap = new HashMap<>();
    //已经获取到打卡记录的月份
    private StringBuffer loggingBuffer = new StringBuffer();
    // 当前选中的对象
    private PunchBean selectPunch;

    /**
     * 设置布局文件
     *
     * @return
     */
    @Override
    public int getLayoutId() {
        return R.layout.activity_punch_logging;
    }

    /**
     * 设置titlebar
     * <p>
     * 延伸到顶部
     */
    @Override
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(false)
                //解决软键盘与底部输入框冲突问题
                .keyboardEnable(true)
                .init();
    }

    /**
     * 加载布局文件-
     */
    @Override
    public void initView() {
        calendarView.setMonthView(MyMonthView.class);
        calendarView.setWeekView(MyWeekView.class);
        //设置当前月份
        titleMonth.setText(calendarView.getCurYear() + "年" + calendarView.getCurMonth() + "月");
        //设置滑动月份监听
        calendarView.setOnMonthChangeListener(this);
        calendarView.setOnCalendarSelectListener(this);
        //返回按钮绑定事件
        backButton.setOnClickListener(clickProxy);
        // 设置规定的打卡时间
        UserIdentify userIdentify = MediumApplication.getUserIdentify();
        // 上午打卡
        if (!TextUtils.isEmpty(userIdentify.getInTime())) {
            settingAmTime.setText(userIdentify.getInTime());
        }
        // 下午
        if (!TextUtils.isEmpty(userIdentify.getOutTime())) {
            settingPmTime.setText(userIdentify.getOutTime());
        }
        String mounthString = String.valueOf(calendarView.getCurMonth());
        if (mounthString.length() == 1) {
            mounthString = "0" + mounthString;
        }
        initData(calendarView.getCurYear() + "-" + mounthString);
        // 设置点击事件
        plAmPart.setOnClickListener(clickProxy);
        plPmPart.setOnClickListener(clickProxy);
    }

    // 设置点击事件
    private ClickProxy clickProxy = new ClickProxy(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.pl_amPart:
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("select_calendar", selectPunch);
                    bundle.putBoolean("isAm", true);
                    ARouterUtils.navigation(RouterPath.TO_PUNCHDETIAL_ACTIVITY, bundle);
                    break;
                case R.id.pl_pmPart:
                    Bundle pmBundle = new Bundle();
                    pmBundle.putSerializable("select_calendar", selectPunch);
                    pmBundle.putBoolean("isAm", false);
                    ARouterUtils.navigation(RouterPath.TO_PUNCHDETIAL_ACTIVITY, pmBundle);
                    break;
                case R.id.pl_backButton:
                    onBackPressed();
                    break;
                default:
            }
        }
    });


    @Override
    public void initData() {

    }

    /**
     * 获取打卡记录
     */
    private void initData(String date) {
        punchPresenter.getPunchLogging(date);
    }


    /**
     * 获取选中的打卡日期
     *
     * @param calendar
     * @param isClick
     */
    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        setSelectCalendarLogging(calendar);
    }

    /**
     * 设置选中的日期的 打卡记录
     *
     * @param calendar
     */
    private void setSelectCalendarLogging(Calendar calendar) {
        selectPunch = listMap.get(calendar.toString());
        if (null != selectPunch) {
            // 有今天的打卡记录  -- 设置下打卡状态  有以下集中情况
            // 1：正常打卡
            // 2：未正常打开（a：只有上班记录 b:上班下班均有 但有异常）
            // 所以需要判断一下是否有打卡记录 再来设置打卡信息备注
            //设置上班打卡记录
            setLoggingText(getPunchStatusString(selectPunch.getInStatus(), true),
                    selectPunch.getInTime(), true);
            //设置下班打卡记录
            setLoggingText(getPunchStatusString(selectPunch.getOutStatus(), false),
                    selectPunch.getOutTime(), false);
            // 设置字体颜色 AM
            setViewColor("0".equals(selectPunch.getInStatus()), true);
            //PM
            setViewColor("0".equals(selectPunch.getOutStatus()), false);
        } else {
            // 没有当天的打卡记录
            amLogging.setText("未打卡");
            setViewColor(false, true);
            pmLogging.setText("未打卡");
            setViewColor(false, false);
        }
    }


    /**
     * 设置正常 和异常状态的字体颜色
     *
     * @param isNormal 打卡状态是否正常
     * @param isAm     是
     */
    private void setViewColor(boolean isNormal, boolean isAm) {
        // 如果是正常  设置为绿色 否设置为红色
        int colorInt = getResources().getColor(R.color.normal_punch_color);
        if (!isNormal) {
            colorInt = getResources().getColor(R.color.abnormal_punch_color);
        }
        if (isAm) {
            amTextView.setTextColor(colorInt);
            ViewBgUtils.setThemeButtonViewBackground(circleImgAm, colorInt);
        } else {
            pmTextView.setTextColor(colorInt);
            //设置圆圈背景色
            ViewBgUtils.setThemeButtonViewBackground(circleImgPm, colorInt);
        }
    }


    /**
     * 设置打卡记录内容
     */
    private void setLoggingText(String statusString, String time, boolean isApm) {
        if (!TextUtils.isEmpty(statusString)) {
            //如果有打卡记录
            if (isApm) {
                amLogging.setText(statusString + "（" + time + "）");
            } else {
                pmLogging.setText(statusString + "（" + time + "）");
            }
        } else {
            if (isApm) {
                amLogging.setText("未打卡");
            } else {
                pmLogging.setText("未打卡");
            }
        }
    }


    /**
     * 获取打卡状态 文字描述
     *
     * @return
     */
    private String getPunchStatusString(String status, boolean isAm) {
        String statusString = "";
        if (!TextUtils.isEmpty(status)) {
            switch (status) {
                case "0":
                    statusString = "正常打卡";
                    break;
                case "1":
                    if (isAm) {
                        statusString = "迟到";
                    } else {
                        statusString = "早退";
                    }
                    break;

                case "2":
                    statusString = "范围外";
                    break;

                case "3":
                    if (isAm) {
                        statusString = "范围外，迟到打卡";
                    } else {
                        statusString = "范围外，早退打卡";
                    }
                    break;
                default:
            }
        }
        return statusString;
    }


    /**
     * 切换月份监听
     *
     * @param year
     * @param month
     */
    @Override
    public void onMonthChange(int year, int month) {
        titleMonth.setText(year + "年" + month + "月");
        //--滑动月份的时候  获取该月的打卡记录 --如果已经获取过的
        // 不在获取了，所以需要设置个标志 判断是否已经或去过该月的记录了
        if (loggingBuffer.length() > 0 && loggingBuffer.toString().contains(year + "-" + month)) {
            //不在获取数据了
        } else {
            // 没有当月的记录  需要获取记录去--
            initData(year + "-" + month);
        }
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    /**
     * 设置用户的打卡记录
     *
     * @param list
     */
    @Override
    public void setUserPunchInfo(List<PunchBean> list) {
        if (null != list && !list.isEmpty()) {
            // 设置当天的打卡信息  绘制日历View
            for (int i = 0; i < list.size(); i++) {
                PunchBean item = (PunchBean) list.get(i);
                String date = item.getDate();
                String array[] = date.split("-");
                //获取该月的记录 2012-12
                loggingBuffer.append(array[0] + "-" + array[1]);
                Calendar calendar;
                if ("0".equals(item.getInStatus()) && "0".equals(item.getOutStatus())) {
                    //正常状态 -- 设置年月日
                    calendar = getSchemeCalendar(Integer.valueOf(array[0]),
                            Integer.valueOf(array[1]), Integer.valueOf(array[2]), "0");
                } else {
                    calendar = getSchemeCalendar(Integer.valueOf(array[0]),
                            Integer.valueOf(array[1]), Integer.valueOf(array[2]), "1");
                }
                dataMap.put(calendar.toString(), calendar);
                listMap.put(calendar.toString(), item);
            }
            // 绘制日历UI
            calendarView.setSchemeDate(dataMap);
            // 设置选中日期的记录--
            setSelectCalendarLogging(calendarView.getSelectedCalendar());
        }
    }

    @Override
    public void result(Results response) {

    }

    @Override
    public void punchFail() {

    }

    /**
     * 设置打卡记录点==
     *
     * @param year
     * @param month
     * @param day
     * @param text
     * @return
     */
    @SuppressWarnings("all")
    private Calendar getSchemeCalendar(int year, int month, int day, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setScheme(text);
        return calendar;
    }
}
